package com.jz.pay.config;

import com.jz.pay.factories.BornFactory;
import com.jz.pay.factories.DieFactory;
import com.jz.pay.factories.FactoryManager;
import com.jz.pay.factories.tmp.BornProcess;
import com.jz.pay.factories.tmp.DieProcess;
import com.jz.pay.utils.lock.RedisLock;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class ApplicationContextConfig {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private int redisPort;
    @Value("${spring.redis.password}")
    private String redisPassword;
    @Value("${spring.redis.timeout}")
    private int redisTimeout;

    @ConfigurationProperties(prefix = "spring.redis.jedis.pool")
    @Bean
    public JedisPoolConfig getJedisPoolConfig(){
        JedisPoolConfig JedisPoolConfig = new JedisPoolConfig();
        JedisPoolConfig.setTestOnBorrow(false);
        JedisPoolConfig.setTestOnReturn(false);
        JedisPoolConfig.setTestOnCreate(true);
        return JedisPoolConfig;
    }

    @Bean
    public JedisPool getJedisPool(JedisPoolConfig JedisPoolConfig){
        String host = redisHost;
        int port = redisPort;
        int timeout = redisTimeout;
        String password = redisPassword;
        JedisPool jedisPool = new JedisPool(JedisPoolConfig,host,port,timeout,password);
        return jedisPool;
    }

    @Bean
    public FactoryManager getFactoryManager(){
        FactoryManager factoryManager = new FactoryManager();
        factoryManager.add(new BornFactory());
        factoryManager.add(new DieFactory());
        factoryManager.addProcess(new DieProcess());
        factoryManager.addProcess(new BornProcess());
        return factoryManager;
    }


//    @Bean
//    public RedisTemplate<String, Serializable> getRedisTemplate(){
//        return new RedisTemplate<String, Serializable>();
//    }

    @Bean
    public RedissonClient getRedissonClient(){
        Config cfg = new Config();
//        SingleServerConfig sfg = cfg.useSingleServer().setAddress("redis://localhost:6379").setPassword("123456").setDatabase(1);
        SingleServerConfig sfg = cfg.useSingleServer().setAddress("redis://"+redisHost+":"+redisPort).setPassword(redisPassword).setDatabase(1);
        RedissonClient redissonClient = Redisson.create(cfg);
        RedisLock.setRedissonClient(redissonClient);
        return redissonClient;
    }
}